<template>
  <div>
    <el-upload
      :action="useOss ? ossUploadUrl : minioUploadUrl"
      :data="useOss ? dataObj : null"
      list-type="picture-card"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
      :limit="maxCount"
      :on-exceed="handleExceed"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog v-model="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { policy } from '@/api/oss'
import { ElMessage } from 'element-plus'
import { ref, computed } from 'vue'
const emit = defineEmits(['input'])

defineOptions({
  name: 'MultiUpload',
})
const props = defineProps({
  value: {
    type: Array,
    default: () => [],
  },
  maxCount: {
    type: Number,
    default: 5,
  },
})
const dataObj = ref({
  policy: '',
  signature: '',
  key: '',
  ossaccessKeyId: '',
  dir: '',
  host: '',
})
const dialogVisible = ref(false)
const dialogImageUrl = ref(null)
const useOss = ref(false) //使用oss->true;使用MinIO->false
const ossUploadUrl = 'http://macro-oss.oss-cn-shenzhen.aliyuncs.com'
const minioUploadUrl = 'http://localhost:8080/minio/upload'
const fileList = computed(() => {
  let fileList = []
  for (let i = 0; i < props.value.length; i++) {
    fileList.push({ url: props.value[i] })
  }
  return fileList
})
function emitInput(fileList) {
  let value = []
  for (let i = 0; i < fileList.length; i++) {
    value.push(fileList[i].url)
  }
  emit('input', value)
}
function handleRemove(file, fileList) {
  emitInput(fileList)
}
function handlePreview(file) {
  dialogVisible.value = true
  dialogImageUrl.value = file.url
}
function beforeUpload(file) {
  if (!useOss.value) {
    //不使用oss不需要获取策略
    return true
  }
  return new Promise((resolve, reject) => {
    policy().then((response) => {
      dataObj.value.policy = response.data.policy
      dataObj.value.signature = response.data.signature
      dataObj.value.ossaccessKeyId = response.data.accessKeyId
      dataObj.value.key = response.data.dir + '/${filename}'
      dataObj.value.dir = response.data.dir
      dataObj.value.host = response.data.host
      resolve(true)
    })
  })
}
function handleUploadSuccess(res, file) {
  let url = dataObj.value.host + '/' + dataObj.value.dir + '/' + file.name
  if (!useOss.value) {
    //不使用oss直接获取图片路径
    url = res.data.url
  }
  fileList.value.push({ name: file.name, url: url })
  emitInput(fileList.value)
}
function handleExceed(files, fileList) {
  ElMessage.success({
    message: '最多只能上传' + props.maxCount + '张图片',
    type: 'warning',
  })
}
</script>
<style></style>
